package com.controller;

import com.dao.CommentDao;
import com.dao.EnvelopeDao;
import com.dao.NoteDao;
import com.po.Comment;
import com.po.Envelope;
import com.po.Note;
import com.utils.JDBCUnits;
import com.po.User;
import com.utils.MD5;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.List;

@WebServlet({"/login", "/register", "/exit", "/selectPassword", "/touristLogin", "/tourist/selectNote",
        "/tourist/selectEnvelope", "/tourist/comment"})
public class LoginSystem extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String servletPath = request.getServletPath();
        if ("/login".equals(servletPath)) {
            dologin(request, response);
        } else if ("/register".equals(servletPath)) {
            doRegister(request, response);
        } else if ("/exit".equals(servletPath)) {
            doExit(request, response);
        } else if ("/touristLogin".equals(servletPath)) {
            doTourist(request, response);
        } else if ("/tourist/selectNote".equals(servletPath)) {
            doTouristNote(request, response);
        } else if ("/tourist/selectEnvelope".equals(servletPath)) {
            doSelectEnvelope(request, response);
        } else if ("/tourist/comment".equals(servletPath)) {
            doComment(request, response);
        }
    }

    private void doComment(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        HttpSession session = request.getSession(false);
        int note_id = Integer.parseInt(request.getParameter("note_id"));
        String note_name = request.getParameter("note_name");
        String note_content = request.getParameter("note_content");
        request.setAttribute("note_id", note_id);
        request.setAttribute("note_name", note_name);
        request.setAttribute("note_content", note_content);

        List<Comment> comment = CommentDao.getComment(note_id);
        request.setAttribute("comment", comment);
        request.getRequestDispatcher("/comment/touristComment.jsp").forward(request, response);
    }

    private void doSelectEnvelope(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        request.setCharacterEncoding("UTF-8");
        String envelope_name = request.getParameter("envelope_name");
        List<Envelope> envelopes = EnvelopeDao.selectEnvelopes(envelope_name);
        if (envelopes.isEmpty()) {
            out.println("对不起，没有此信封");
        } else {
            request.setAttribute("envelopes", envelopes);
            request.getRequestDispatcher("/envelope/touristSelectEnvelope.jsp").forward(request, response);
        }
    }

    private void doTouristNote(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        request.setCharacterEncoding("UTF-8");
        int envelope_id = Integer.parseInt(request.getParameter("envelope_id"));
        String envelope_name = request.getParameter("envelope_name");

        List<Note> notes = NoteDao.getNotes(envelope_id);
        request.setAttribute("notes", notes);
        request.getRequestDispatcher("/note/touristNote.jsp").forward(request, response);
    }

    private void doTourist(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        List<Envelope> envelopes = EnvelopeDao.getOpenEnvelope(0);
        request.setAttribute("envelopes", envelopes);
        request.getRequestDispatcher("/envelope/touristEnvelope.jsp").forward(request, response);
    }


    private void doExit(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.invalidate();
            response.sendRedirect(request.getContextPath() + "/index.jsp");
        }
    }

    private void doRegister(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String netName = request.getParameter("netName");
        String sex = request.getParameter("sex");

        Connection c = null;
        PreparedStatement ps = null;
        int count;
        try {
            c = JDBCUnits.getConnectino();
            String sql = "insert into t_usr(username,password,name,sex,create_time) values(?,?,?,?,now())";
            ps = c.prepareStatement(sql);
            ps.setString(1, username);
            ps.setString(2, MD5.getMD5String(password));
            ps.setString(3, netName);

            if ("male".equals(sex)) {
                ps.setString(4, "先生");
            } else {
                ps.setString(4, "女士");
            }

            count = ps.executeUpdate();

            if (count == 1) {
                out.print("注册成功<br>");
                out.print("<a href=\"" + request.getContextPath() + "/index.jsp\">返回登录页面</a>");
            } else {
                out.print("用户名已经存在<br>");
                out.print("<a href=\"" + request.getContextPath() + "/register.jsp>返回注册页面</a>");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    private void dologin(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        Connection c = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        int id = 0;
        String name = null;
        String sex = null;
        String duty = null;
        String status = null;
        boolean success = false;
        User user = new User();
        try {
            c = JDBCUnits.getConnectino();
            String sql = "select * from t_usr where username = ? and password = ?";
            ps = c.prepareStatement(sql);
            ps.setString(1, username);
            ps.setString(2, MD5.getMD5String(password));
            rs = ps.executeQuery();
            while (rs.next()) {
                name = rs.getString("name");
                id = rs.getInt("id");
                sex = rs.getString("sex");
                Date create_time = rs.getDate("create_time");
                user.setName(name);
                user.setId(id);
                user.setSex(sex);
                user.setGrade(create_time);
                duty = rs.getString("duty");
                status = rs.getString("status");
                success = true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUnits.close(c, ps, rs);
        }
        if (!"冻结".equals(status)) {
            if (success) {
                request.setAttribute("user", user);
                HttpSession session = request.getSession();
                session.setAttribute("id", id);
                session.setAttribute("name", name);
                session.setAttribute("sex", sex);
                session.setAttribute("grade", user.getGrade());
                session.setAttribute("duty", duty);
                request.getRequestDispatcher("success.jsp").forward(request, response);
            } else {
                out.println("账号或者密码不正确");
                out.println("<a href=\"" + request.getContextPath() + "/index.jsp\">请重新登录</a>");
            }
        }else{
            out.println("你的账号被管理员冻结，无法登录");
            out.println("<a href=\"" + request.getContextPath() + "/administrator/requestFreezing.jsp?user_id="+ id+"\">前往申请解冻</a>");
        }
    }

}
